using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using TTDotNet.Engine.Vehicles;
using TTDotNet.Util;
using TTDotNet.Engine.ThreeDEngine;
using Microsoft.Samples.DirectX.UtilityToolkit;

namespace TTDotNet.Engine.Files
{
    public class VehicleLoader
    {
        string path = Utility.FindMediaFile("data/vehicles/road_vehicles.xml");
        List<VehicleInfo> vehicleList = new List<VehicleInfo>();

        public VehicleLoader()
        {
            loadRoadVehicles();
        }

        public List<VehicleInfo> getRoadVehicles()
        {
            return vehicleList;
        }

        private void loadRoadVehicles()
        {
            string str = null;

            try
            {
                if (File.Exists(path))
                {
                    FileStream roadIn = new FileStream(path, FileMode.Open);
                    StreamReader sr = new StreamReader(roadIn);

                    while ((str = sr.ReadLine()) != null)
                    {
                        VehicleInfo info = buildInfo(str);
                        if (info != null)
                        {
                            vehicleList.Add(info);
                        }
                    }

                    sr.Close();
                    roadIn.Close();
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Error loading vehicle file");
                }


            }
            catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.Message); }

        }

        private VehicleInfo buildInfo(string str)
        {
            VehicleInfo info = null;
            string[] delims = { "," };

            try
            {
                string[] data = str.Trim().Split(delims, StringSplitOptions.RemoveEmptyEntries);


                if (data.Length != 7)
                {
                    System.Windows.Forms.MessageBox.Show("Error loading vehicles\n Line" + str + " is malformed.");
                }
                else
                {
                    string model = data[0];
                    int year = Int32.Parse(data[1]);
                    int speed = Int32.Parse(data[2]);
                    int horsepower = Int32.Parse(data[3]);
                    int cap = Int32.Parse(data[4]);
                    CargoType type = (CargoType)Enum.Parse(typeof(CargoType), data[5]);
                    string meshpath = data[6];
                    
                    info = new VehicleInfo(VehicleType.Road, model, year, speed, horsepower, cap, type, meshpath);
                }
            }
            catch (Exception e) {
                System.Windows.Forms.MessageBox.Show("There has been an error creating the vehicle info: \n" + e.Message);
            }

            return info;

        }

    }

    
}
